package com.ydzt.fanka.server.space.errorhanding;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;

import com.ydzt.fanka.server.domain.BufferRecord;
import com.ydzt.fanka.server.init.InitData;
import com.ydzt.fanka.server.persistence.BufferStore;
import com.ydzt.fanka.server.utils.IOUtil;

/*
 * 错误处理进程
 * 将因为连接数据库失败而未发送成功的报文，先放入error_pkg/jdbc_connect_error文件夹内
 * 此线程负责将error_pkg/jdbc_connect_error内的报文 重新放入buffer文件夹内 尝试重新发送
 * */
public class ErrServer extends Thread{
	static Logger logger = Logger.getLogger(ErrServer.class.getName());
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	public void run(){
		while(true){
			Date today = new Date();
			BufferRecord record = new BufferRecord();
			long size = 0;
			byte[] pkg = null;
			StringBuilder strBuilder = new StringBuilder();
			strBuilder.append(InitData.errorPath);
			strBuilder.append("/");
			String todayFile = sdf.format(today);
			strBuilder.append(todayFile);
			strBuilder.append("/");
			strBuilder.append(InitData.jdbc_connect_error);
			String path = strBuilder.toString();
			strBuilder.delete(0, strBuilder.length());
			File f = new File(path);
			if(f != null){
				File flist[] = f.listFiles();
				if(flist != null){
					size = flist.length;
					if(size != 0){
						File file = flist[0];
						try {
							pkg = IOUtil.toByteArrayTraditional(file.getAbsolutePath());
							if(pkg.length != 0){
								record.setBufferContent(pkg);
								record.setBufferId(file.getName().split("\\.")[0]);
								if(file.isFile() && file.exists()){
									boolean isDelete = file.delete();
									if(isDelete){
										BufferStore.writePackageIntoFile(record);
										
									}
									else{
										BufferStore.writePackageIntoErrorFile(record, InitData.write_into_buffer_error);
									}
								}
							}
							else{
								//logger.error("在buffer中取到长度为0的空文件");
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
						finally{
							pkg = null;
							record = null;
							flist = null;
						}
					}
					else{
						try {
							Thread.sleep(60000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
}
